package com.heima.admin.aspect;



import com.alibaba.fastjson.JSON;

import com.heima.model.admin.pojos.LogsMG;
import com.heima.model.wemedia.pojos.WmNews;
import com.heima.utils.common.WmThreadLocalUtil;
import io.swagger.annotations.Api;

import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.AfterThrowing;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.reflect.MethodSignature;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.Method;
import java.time.LocalDateTime;
import java.util.Arrays;

@Aspect
@Component
@Slf4j
@RequiredArgsConstructor
public class OperateLogAspect {

    private final MongoTemplate mongoTemplate;

    @Autowired
    HttpServletRequest request;

    @Around("execution(* com.heima.admin.controller..*.*(..)) && @annotation(com.heima.admin.annotation.OperationFill) ")
    public Object recodeLog(ProceedingJoinPoint joinPoint) throws Throwable {
        log.info("开始日志创建");

        LogsMG logs = new LogsMG();

        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        assert attributes != null;
        HttpServletRequest request = attributes.getRequest();

        // 获取HTTP请求方法
        String httpMethod = request.getMethod();
        logs.setURLMethod(httpMethod);

        Class<?> targetClass = joinPoint.getTarget().getClass();

        // 获取类上的注解
        Api classAnnotation = targetClass.getAnnotation(Api.class);


        //获取HTTP请求路径
        String httpPath = request.getRequestURI();
        logs.setURL(httpPath);


        //操作时间
        LocalDateTime operTime = LocalDateTime.now();
        logs.setTime(operTime);

        //获取方法执行时的参数
        Object[] args = joinPoint.getArgs();
        logs.setIntoTheParameters(Arrays.toString(args));
        logs.setUserName("admin");
        mongoTemplate.save(logs);
        log.info("记录成功日志");

        //获取方法返回值
        Object result = joinPoint.proceed();


        return result;

    }
}

